package com.wzk.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wzk.pojo.User;
import com.wzk.service.impl.UserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class
UserRealm extends AuthorizingRealm{
    @Autowired
    private UserServiceImpl userService;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        info.addStringPermission("user:add");

        //拿到当前登录的对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();

        //设置用户权限
        info.addStringPermission(currentUser.getPerms());


        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了认证");

//        String name = "root";
//        String password = "123456";

//        if (!userToken.getUsername().equals(name)){
//            return null;
//        }

        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("name",userToken.getUsername());
        User user = userService.getOne(wrapper);

        if (user==null){
            //return null 会自动抛出UnknownAccountException异常
            return null;
        }




        //密码认证 shiro做
        return new SimpleAuthenticationInfo(user,user.getPwd(),"");

    }
}
